package com.example.flowabledemo.config.exception;

import com.example.flowabledemo.common.HttpCode;
import com.example.flowabledemo.data.dto.ResponseResult;
import java.lang.reflect.UndeclaredThrowableException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

/**
 * 自定义错误返回
 */
@ControllerAdvice
public class CustomControllerException {

  Logger logger = LoggerFactory.getLogger("ADVICE");

  @ExceptionHandler(Exception.class)
  public String ex(HttpServletRequest request, HttpServletResponse response, Exception e) {
    if (e instanceof org.springframework.boot.context.properties.bind.BindException) {
      System.out.println(111);
    }
    request.setAttribute("errorMessage", e);
    logger.error("RuntimeException-异常请求-{}?{},远程地址-{} 异常信息-{}",
        request.getRequestURL(), request.getQueryString(), request.getRemoteAddr(), e.getMessage());
    return "status/500";
  }

  @ExceptionHandler(BindException.class)
  @ResponseBody
  public ResponseResult BindException(HttpServletRequest request, HttpServletResponse response, BindException e) {
    BindingResult result = e.getBindingResult();
    StringBuilder errorMsg = new StringBuilder();
    for (ObjectError error : result.getAllErrors()) {
      errorMsg.append(error.getDefaultMessage()).append("，");
    }
    return new ResponseResult(HttpCode.VALIDATION, errorMsg.toString());
  }

  @ExceptionHandler(RuntimeException.class)
  @ResponseBody
  public Object RuntimeException(HttpServletRequest request, HttpServletResponse response, Exception e) {
    if (e instanceof AccessDeniedException) {
      /*log.warn("{} - {}", request.getRequestURL(), e.getMessage());
      return new ResponseResult<>(HttpCode.FAIL, "403，权限不足，无法操作！请联系管理员添加权限。");*/
      request.setAttribute("errorMessage", e);
      return new ModelAndView("status/403");
    }
    if (e instanceof UndeclaredThrowableException) {
      logger.warn("{} - {}", request.getRequestURL(),
          ((UndeclaredThrowableException) e).getUndeclaredThrowable().getMessage());
      return new ResponseResult<>(HttpCode.FAIL, ((UndeclaredThrowableException) e).getUndeclaredThrowable().getMessage());
    }
    request.setAttribute("errorMessage", e);
    logger.error("RuntimeException-异常请求-{}?{},远程地址-{} 异常信息-{}",
        request.getRequestURL(), request.getQueryString(), request.getRemoteAddr(), e.getMessage());
    return new ModelAndView("status/500");
  }


}
